using System;
using System.Net.Sockets;
using System.Text;

namespace fuzzyKittenVNC
{
	public class VNCClientReceiveThread
	{
		private VNCClient client;
		private Socket socket;
		private VNCMessages.VNCServerMessage currentMsg;
		
		public VNCClientReceiveThread(VNCClient client,Socket socket)
		{
			this.socket = socket;
			this.client = client;
		}
		
		public void receive() {
			byte[] msg;
			int received;
			for(;;) {
				msg = new byte[this.socket.ReceiveBufferSize];
				if(!this.socket.Connected)
					break;
				if(!client.isReady()) {
					throw new VNCConnectionException();
				}
			
				received = this.socket.Receive(msg);
				currentMsg = VNCMessages.VNCServerMessage.createFromStream(msg,this.client);
				
				if(currentMsg == null || received == 0)  {
					if(!client.isReady()) {
						throw new VNCConnectionException();
					}
					continue;
				}	
				currentMsg.updateContent(msg,received);	
				while(currentMsg.bytesMissing > 0) {
					if(!this.socket.Connected) 
						throw new VNCConnectionException();
					received = this.socket.Receive(msg);
					currentMsg.updateContent(msg,received);					
				}
				
				client.handleMessage(currentMsg);
				currentMsg = null;
			}	
		}	
	}
}

